package com.app.util.file.struct;

import java.io.File;
import java.io.IOException;

import com.app.util.file.txt.LineWriter;
import com.app.util.param.Param;
import com.app.util.string.StringUtil;

public class StructFileWriter {

	private Params params = new Params();
	private LineWriter lineWriter;

	private boolean headersWrited = false;

	/**
	 * 构造一个结构文件存储类
	 * 
	 * @param file
	 * @param charset
	 * @throws IOException
	 */
	public StructFileWriter(File file, String charset) throws IOException {
		lineWriter = new LineWriter(file, charset);
	}
 
	/**
	 * 构造一个结构文件存储类
	 * 
	 * @param file
	 * @throws IOException
	 */
	public StructFileWriter(File file) throws IOException {
		lineWriter = new LineWriter(file);
	}

	public void addParam(Param header) {
		params.add(header);
	}

	public void addParam(String name, String value) {
		params.add(new Param(name, value));
	}

	public void addParams(Params params) {
		this.params.putAll(params);
	}

	public Params getParams() {
		return params;
	}

	private void writerParams() throws IOException {
		if (headersWrited) {
			return;
		}
		headersWrited = true;
		lineWriter.writeLine(new Param("# header, count", "" + params.size()).toString());
		lineWriter.writeLine(StringUtil.toString(params));
	}

	public void write(char c) throws IOException {
		writerParams();
		lineWriter.write(c);
	}

	public void write(String s) throws IOException {
		writerParams();
		lineWriter.write(s);
	}

	public void writeLine(String s) throws IOException {
		writerParams();
		lineWriter.writeLine(s);
	}

	public void close() throws IOException {
		lineWriter.close();
	}
}
